package cn.cloud.all.security.oauth2.resource;

import cn.cloud.all.security.oauth2.client.token.AccessTokenRequest;

public abstract class AbstractRedirectResourceDetails extends BaseOAuth2ProtectedResourceDetails {

    private String preEstablishedRedirectUri;

    private String userAuthorizationUri;

    private boolean useCurrentUri = true;

    public void setUseCurrentUri(boolean useCurrentUri) {
        this.useCurrentUri = useCurrentUri;
    }

    public boolean isUseCurrentUri() {
        return useCurrentUri;
    }

    public String getUserAuthorizationUri() {
        return userAuthorizationUri;
    }

    public void setUserAuthorizationUri(String userAuthorizationUri) {
        this.userAuthorizationUri = userAuthorizationUri;
    }

    public String getPreEstablishedRedirectUri() {
        return preEstablishedRedirectUri;
    }

    public void setPreEstablishedRedirectUri(String preEstablishedRedirectUri) {
        this.preEstablishedRedirectUri = preEstablishedRedirectUri;
    }

    public String getRedirectUri(AccessTokenRequest request) {
        String redirectUri = request.getFirst("redirect_uri");

        if (redirectUri == null && request.getCurrentUri() != null && useCurrentUri) {
            redirectUri = request.getCurrentUri();
        }

        if (redirectUri == null && getPreEstablishedRedirectUri() != null) {
            // Override the redirect_uri if it is pre-registered
            redirectUri = getPreEstablishedRedirectUri();
        }

        return redirectUri;
    }
}
